package com.google.gwt.sample.stockwatcher.client.entrypoint;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.sample.stockwatcher.client.Idd;
import com.google.gwt.sample.stockwatcher.client.StockAdd;
import com.google.gwt.sample.stockwatcher.client.StockAddAsync;
import com.google.gwt.sample.stockwatcher.client.StockEdit;
import com.google.gwt.sample.stockwatcher.client.StockEditAsync;
import com.google.gwt.sample.stockwatcher.client.StockPrice;
import com.google.gwt.sample.stockwatcher.client.StockPriceService;
import com.google.gwt.sample.stockwatcher.client.StockPriceService2;
import com.google.gwt.sample.stockwatcher.client.StockPriceService2Async;
import com.google.gwt.sample.stockwatcher.client.StockPriceServiceAsync;
import com.google.gwt.sample.stockwatcher.server.StockPriceServiceImpl2;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.KeyboardListenerAdapter;
import com.google.gwt.user.client.Window;
import java.util.ArrayList;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Random;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.NumberFormat;
import java.util.Date;


import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class StockWatcher implements EntryPoint {
	private final StockPriceService2Async greetingService = GWT.create(StockPriceService2.class);
	private final StockAddAsync Service = GWT.create(StockAdd.class);
	private final StockEditAsync editService = GWT.create(StockEdit.class);
	private VerticalPanel mainPanel = new VerticalPanel();
	private FlexTable stocksFlexTable = new FlexTable();
	private HorizontalPanel addPanel = new HorizontalPanel();
	private TextBox textname = new TextBox();
	private TextBox textsername = new TextBox();
	private TextBox textphone = new TextBox();
	private Button addButton = new Button("Add");
	private Label lastUpdatedLabel = new Label();
	private static final int REFRESH_INTERVAL = 5000; // ms
	private StockPriceServiceAsync stockPriceSvc;

	public void onModuleLoad() {
		stocksFlexTable.setText(0, 0, "Name");
		stocksFlexTable.setText(0, 1, "Sername");
		stocksFlexTable.setText(0, 2, "Phone");
		stocksFlexTable.setText(0, 3, "Remove");
		stocksFlexTable.setText(0, 4, "Edit");
		// set up event listeners for adding a new stock
		addButton.addClickListener(new ClickListener() {
			public void onClick(Widget sender) {
				addStock();
			}
			});
		
		// assemble Add Stock panel		
		addPanel.add(textname);
		addPanel.add(textsername);
		addPanel.add(textphone);
		addPanel.add(addButton);

		mainPanel.add(stocksFlexTable);
		mainPanel.add(addPanel);
		mainPanel.add(lastUpdatedLabel);

		//RootPanel.get().add(newSymbolTextBox);
		RootPanel.get("stockList").add(mainPanel);
		
		// setup timer to refresh list automatically
		Timer refreshTimer = new Timer() {
			public void run() {
			//	refreshWatchList();
				}
			};
			refreshTimer.scheduleRepeating(REFRESH_INTERVAL);
			// move cursor focus to the text box
			textname.setFocus(true);
			refreshWatchList();
	}
	private void addStock() {
		final String name = textname.getText();
		//textname.setFocus(true);
		final String sername = textsername.getText();
		//textsername.setFocus(true);
		final String phone = textphone.getText();
		//textphone.setFocus(true);
		StockPrice addPrice=new StockPrice();
		addPrice.setName(name);
		addPrice.setSername(sername);
		addPrice.setPhone(phone);
		
		Service.getPrice(addPrice, new AsyncCallback<StockPrice>() {
	        public void onFailure(Throwable caught) {
	        	refreshWatchList();
	            }
	        public void onSuccess(StockPrice result) {
	    		refreshWatchList();
	        }
		});
		
	/*	if (!name.matches("^[0-9a-zA-Z\\.]{1,10}$"))
		{
			Window.alert("'" + textname + "' is not a valid symbol.");
			textname.selectAll();
			return;
			}*/
		//textname.setText("");

	}
	private void refreshWatchList() {
		if (stockPriceSvc == null) {
			stockPriceSvc = GWT.create(StockPriceService.class);
			}
		AsyncCallback<StockPrice[]> callback = new AsyncCallback<StockPrice[]>() {
			public void onFailure(Throwable caught) {
			}
			public void onSuccess(StockPrice[] result) {
				updateTable(result);
			}
		};
		//stockPriceSvc.getPrices(stocks.toArray(new StockPrice[0]), callback);
		stockPriceSvc.getPrices(new StockPrice[0], callback);
		}

	private void updateTable(StockPrice[] prices) {
		System.out.println(prices.length);
		for (int i=0; i<prices.length; i++) {
			stocksFlexTable.setText(i+1, 0, prices[i].getName());
			stocksFlexTable.setText(i+1, 1, prices[i].getSername());
			stocksFlexTable.setText(i+1, 2, prices[i].getPhone());
			final int removedIndex = prices[i].getId();
			Button removeStock = new Button("x");
			Button editStock = new Button("...");
			removeStock.addClickListener(new ClickListener(){
				public void onClick(Widget sender) {
					sendRemoveId(removedIndex);
					refreshWatchList();
					return;
				}});
			editStock.addClickListener(new ClickListener(){
				public void onClick(Widget sender) {
					edit(removedIndex);
					refreshWatchList();
					return;
				}});
			
			stocksFlexTable.setWidget(i+1, 3, removeStock);
			stocksFlexTable.setWidget(i+1, 4, editStock);
			}
		lastUpdatedLabel.setText("Last update : " +DateTimeFormat.getMediumDateTimeFormat().format(new Date()));
	//	refreshWatchList();
		}
	private void sendRemoveId(int removedIndex){
		int rem=removedIndex;
		Idd removeId = new Idd();
		removeId.setId(rem);
		greetingService.getId(removeId, new AsyncCallback<Idd>() {
	        public void onFailure(Throwable caught) {
	        	refreshWatchList();
	            }
	        public void onSuccess(Idd result) {
	    		refreshWatchList();
	        }
		});
	}
	private void edit(int removedIndex){
		final String name = textname.getText();
		//textname.setFocus(true);
		final String sername = textsername.getText();
		//textsername.setFocus(true);
		final String phone = textphone.getText();
		//textphone.setFocus(true);
		StockPrice editPrice=new StockPrice();
		editPrice.setId(removedIndex);
		editPrice.setName(name);
		editPrice.setSername(sername);
		editPrice.setPhone(phone);
		int rem=removedIndex;
	//	Id removeId = new Id();
	//	removeId.setId(rem);
		editService.getPrice(editPrice, new AsyncCallback<StockPrice>() {
	        public void onFailure(Throwable caught) {
	            }
			@Override
			public void onSuccess(StockPrice result) {
				// TODO Auto-generated method stub
				
			}
		});
	}
}